local SpeechToConfirm = {}

local function ConfirmSpeech (text)
	for k,v in pairs (SpeechToConfirm) do
		if v[1] == text then
			print ("confirmed", text)
			SpeechToConfirm[k] = nil
		end
	end
end

local function RepeatFails ()
	for k,v in pairs (SpeechToConfirm) do
		if v[2] + 1 > CurTime() then
			RunConsoleCommand ("say", v[1])
		end
	end
end

hook.Add ("Think", "RepeatFails", RepeatFails)

function AttemptToSay (text)
	print ("attempting", text)
	table.insert (SpeechToConfirm, {text, CurTime()})
	RunConsoleCommand ("say", text)
end

local function attemptSayCC (ply, cmd, args)
	print ("throwing attempt")
	AttemptToSay (args[1])
end

concommand.Add ("attemptSay", attemptSayCC)

function DraughtsChatHook (pid, pname, text)
	print (pid, pname, text)
	if Entity(pid) == LocalPlayer() then
		print ("attempt confirmation", text)
		ConfirmSpeech (text)
	end
	if tgm.CurrentGame and tgm.CurrentGame.codename == "draughts" then
		tgm.CurrentGame:ChatMessageReceived (Entity(pid), text)
	end
end

hook.Add ("ChatText", "DraughtsChatHook", DraughtsChatHook)

function GAME:ChatMessageReceived (ply, text)
	print (ply, text)
	if string.sub (text, 1, 11) == "[DRAUGHTS] " then
		--ok, check for player
		text = string.sub (text, 13)
		print (text)
		if tonumber (string.sub (text, 1, string.find (text, "]") - 1)) == LocalPlayer():UserID() then
			text = string.sub (text, string.find (text, "[", 1, true) + 1, string.len (text) - 1)
			print (text)
			local args = string.Explode (":", text)
			PrintTable (args)
			local func = "Comm_"..args[1]
			if func then
				table.remove (args, 1)
				print (func)
				PrintTable (args)
				if self[func] then
					self[func](self,ply,unpack(args))
				end
			end
		end
	end
end

function GAME:Comm_StartGame (ply,side)
	print (ply, side)
	if self.Opponent then return end --already playing
	if side == "1" then side = 2 else side = 1 end --we play the other side
	self.Opponent = ply
	self.PlayingAs = side
	print ("playing as", side)
	self:StartGame()
	print ("attempting say...")
	AttemptToSay ("[DRAUGHTS] ["..ply:UserID().."] [ConfirmGame:"..side.."]")
end

function GAME:Comm_ConfirmGame (ply,side)
	print (ply, side)
	if self.Opponent then return end --already playing (how??)
	if side == "1" then side = 2 else side = 1 end --we play the other side
	self.Opponent = ply
	self.PlayingAs = side
	print ("playing as", side)
	self:StartGame()
end

function GAME:Comm_MakeMove (ply,sx,sy,x,y)
	if self.Opponent == ply then
		print ("opponent moving", sx, sy, x, y)
		local anotherTurn = self:DoMove (tonumber(sx),tonumber(sy),tonumber(x),tonumber(y))
		if not anotherTurn then
			self.Turn = self.PlayingAs
		end
	end
end
